package com.antdesignbackend.backend.controller;

import com.antdesignbackend.backend.aop.AuthToken;
import com.antdesignbackend.backend.common.returnResult.ReturnVO;
import com.antdesignbackend.backend.entity.FeeType;
import com.antdesignbackend.backend.entity.Shop;
import com.antdesignbackend.backend.entity.entityVo.FeeListVo;
import com.antdesignbackend.backend.entity.entityVo.FeeVo;
import com.antdesignbackend.backend.service.FeeListService;
import com.antdesignbackend.backend.service.FeeService;
import com.antdesignbackend.backend.service.IShopService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.lang.reflect.InvocationTargetException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("//home")
public class HomeController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    ReturnVO result = new ReturnVO();

    @Autowired
    private FeeService feeService;
    @Autowired
    private FeeListService feeListService;
    @Autowired
    private IShopService shopService;

    /**
     * 首页 index
     */
    @GetMapping("/index")
    public String index() {
        // ModelAndView modelAndView = new ModelAndView("client/index");
        return "index";
    }
    /***
     * 前端分页查询
     *
     * @return
     * @throws SecurityException
     * @throws NoSuchMethodException
     * @throws InvocationTargetException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    @PostMapping("/tableSearch")
    @ResponseBody
    public ReturnVO tableSearch(@RequestBody FeeVo data) throws NoSuchMethodException, SecurityException,
            IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        result = new ReturnVO();
        List<FeeVo> datalist=new ArrayList<>();
        QueryWrapper<FeeVo> wrapper =new QueryWrapper<>();
//        if(data.getName()!=null&& !data.getName().equals(""))
//        {
//            //wrapper.and(wra -> wra.le("t.createTime",data.getEndTime()));
//            wrapper.like("t.name",data.getName());
//        }
        wrapper.gt("dueAmount",0);
        //先统计满足条件的数据总数，因为sql 不包括排序
        int total=feeService.countView(wrapper);
        result.setTotal(total);
        //再查询
        if(total>=0)
        {
            datalist= feeService.searchView(wrapper.orderByAsc("t.feeData"),new Page<>(data.getPageIndex(),data.getPageSize()));

        }
        result.setData(datalist);
        return result;


    }

    /**
     * 获得本月商户缴费情况统计
     */
    @ResponseBody
    @GetMapping(value = "/getShopFee")
    @AuthToken
    public Map<String,Integer> getShopFee() {
        Map<String,Integer> map=new HashMap<>();
        QueryWrapper<Shop> wrapper =new QueryWrapper<>();
        wrapper.eq("state",1);
        List<Shop> dataList = shopService.getBaseMapper().selectList(wrapper);
        map.put("total",dataList.size());

        DateFormat dfdate = new SimpleDateFormat("yyyy-MM");
        String nowmonth=dfdate.format(new Date());
        QueryWrapper<FeeVo> wrapperfee =new QueryWrapper<>();
        wrapperfee.eq("feeYearMonth",nowmonth);
        List<FeeVo> datafeeList = feeService.searchView(wrapperfee,new Page<>(1,99999));
        //已缴费
        map.put("feetotal",datafeeList.stream().filter(s->s.getDueAmount()==0).collect(Collectors.toList()).size());
        //欠费
        map.put("duetotal",datafeeList.stream().filter(s->s.getDueAmount()>0).collect(Collectors.toList()).size());

        return map;
    }
    /**
     * 缴费情况图
     */
    @PostMapping("/getFeeMap")
    @ResponseBody
    public Map<String, Object> getFeeMap(@RequestBody FeeListVo vo) throws Exception {
        Map<String, Object> resultmap= new HashMap<>();
        DateFormat dfmonth = new SimpleDateFormat("MM");
        DateFormat dfyear = new SimpleDateFormat("yyyy");
        String nowmonth=dfmonth.format(new Date());
        String nowyear=dfyear.format(new Date());
        Integer month=Integer.parseInt(nowmonth);
        List<String> typenames=new ArrayList<>();
        List<String> shopnames=new ArrayList<>();
        //先获取收费类目
        List<FeeType> typeList = new ArrayList<>();
        QueryWrapper<FeeType> wrapper =new QueryWrapper<>();
        wrapper.eq("state",1);
        try
        {

            typenames.add("已缴");
            typenames.add("欠费");
            typenames.add("总费用");
            resultmap.put("typenames",typenames);
            //X
            for (int i=1;i<=month;i++) {
                shopnames.add(i+"月");
            }
            resultmap.put("shopnames",shopnames);

            QueryWrapper<FeeVo> wrapperfee =new QueryWrapper<>();
            wrapperfee.ge("t.feeData",nowyear+"-01-01");
            List<FeeVo> datafeeList=feeService.searchView(wrapperfee,new Page<>(1,99999));
            List<Object> series=new ArrayList<>();
            Map<String,Object> valueItem1=new HashMap();
            List<String> amountList=new ArrayList<>();
            List<String> amountdueList=new ArrayList<>();
            List<String> amountfeeList=new ArrayList<>();

            for (int i=1;i<=month;i++) {
                String  yearmonth=nowyear+"-"+String.format("%02d", i);
                List<FeeVo> filterdata=datafeeList.stream().filter(s->s.getFeeYearMonth().equals(yearmonth)).collect(Collectors.toList());
                Double total=filterdata.stream().mapToDouble(FeeVo::getAmount).sum();
                Double totaldue=filterdata.stream().mapToDouble(FeeVo::getDueAmount).sum();
                amountfeeList.add(String.format("%.2f",total-totaldue));
                amountdueList.add(String.format("%.2f",totaldue));
                amountList.add(String.format("%.2f",total));

            }

            valueItem1=new HashMap();
            valueItem1.put("name","已缴");
            valueItem1.put("type","bar");
            valueItem1.put("data",amountfeeList);
            series.add(valueItem1);

            valueItem1=new HashMap();
            valueItem1.put("name","欠费");
            valueItem1.put("type","bar");
            valueItem1.put("data",amountdueList);
            series.add(valueItem1);

            valueItem1=new HashMap();
            valueItem1.put("name","总费用");
            valueItem1.put("type","bar");
            valueItem1.put("data",amountList);
            series.add(valueItem1);
            resultmap.put("series",series);
        }
        catch(Exception ex)
        {
            logger.error(ex.getMessage());
        }

        return resultmap;
    }
}
